package com.fzrskj.cloud.free.api;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.consts.ApiReturnConstant;
import com.fzrskj.cloud.free.consts.WiniisConstant;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.miniservice.utils.MiniServiceRequest;
import com.winiis.component.utils.client.RestClientUtils;
import ms.core.tool.StrTool;

import java.util.Map;

/**
 * SmsDiyAPI.
 *
 * @author zj.
 *         Created on 2019/11/19 0019.
 */
public class SmsDiyAPI implements SmsAPI {
    @Override
    public String send(String param) {
        JSONObject objResult = new JSONObject();
        JSONObject json = JSONObject.parseObject(param);
        String phoneNumber = json.getString("Tel");
        String msgContent = json.getString("Content");
        String sendSmsUrl = DicParamUtils.getParamValue("hlSmsUrl");
        String account = DicParamUtils.getParamValue("hlUsername");
        String password = DicParamUtils.getParamValue("hlToken");

        if (StrTool.isBlankStr(phoneNumber) || StrTool.isBlankStr(msgContent)) {
            objResult.put("code", "-1");
            objResult.put("message", "手机号码或短信内容不能为空");
            return JSONObject.toJSONString(objResult);
        }

        JSONObject data = new JSONObject();
        data.put("account", account);
        data.put("pwd", password);
        data.put("phone", phoneNumber);
        data.put("content", msgContent);

        if (!StrTool.isBlankStr(sendSmsUrl)) {
            RestClientUtils clientUtils = new RestClientUtils();
            clientUtils.post(sendSmsUrl, data);
            if (clientUtils.getReponseStatus() > 299 || clientUtils.getReponseStatus() < 200) {
                objResult.put(ApiReturnConstant.RESULT_CODE, "-11");
                objResult.put(ApiReturnConstant.RESULT_MSG, clientUtils.getClientResponse(String.class));
                return JSONObject.toJSONString(objResult);
            }
        } else {
            MiniServiceRequest miniServiceRequest = new MiniServiceRequest();
            Map result = miniServiceRequest.post(WiniisConstant.MINI_SERVER_CODE_TOOL, "/sms", data, Map.class);
            if (null == result) {
                objResult.put(ApiReturnConstant.RESULT_CODE, "-11");
                objResult.put(ApiReturnConstant.RESULT_MSG, miniServiceRequest.getMsg());
                return JSONObject.toJSONString(objResult);
            }
        }
        objResult.put(ApiReturnConstant.RESULT_CODE, "0");
        objResult.put(ApiReturnConstant.RESULT_MSG, "操作成功");
        return JSONObject.toJSONString(objResult);
    }
}
